#include "file.h"

namespace Opl{ namespace Scripting{ namespace System{ namespace IO{

QString File::ID = "File";

class FilePrivate{
	public:
		FilePrivate():file(0)
		{}

		~FilePrivate() {
			delete file;
		}
		QFile* file;
};

QScriptValue File::construct_Script(QScriptContext *context, QScriptEngine *engine)
{
	if (context->argumentCount() == 1)
		return engine->newQObject(new File(context->argument(0).toString()));

	return engine->newQObject(new File);
}

File::File(const QString& path):
	Opl::Core::EntityObject(0), O_PRIVATE_CREATE(File)
{
	setName(path);
}

File::File() :
	Opl::Core::EntityObject(0), O_PRIVATE_CREATE(File)
{
	O_D(File);	
}

File::~File()
{
	O_PRIVATE_DELETE;
}

QString File::name()const
{
	O_C(File);
	if (d->file)
		return d->file->fileName();

	return QString();
}

QString File::readAllText()
{
	O_D(File);
	if (!d->file)
		return QString();

	if (!d->file->isOpen())
		if (!d->file->open(QIODevice::ReadOnly))
			return QString();

	QTextStream in(d->file);
	return in.readAll();
}

void File::setName(const QString& param)
{
	O_D(File);
	if (d->file == 0)
		d->file = new QFile();

	d->file->setFileName(param);
}

}}}}
